//
//  UIViewController_getInstance.swift
//  MyLibrary
//
//  Created by 周博 on 2020/6/18.
//  Copyright © 2020 ncit. All rights reserved.
//

import UIKit


protocol UIViewControllerProtcol {

}

extension UIViewController: UIViewControllerProtcol {

}

extension UIViewControllerProtcol where Self: UIViewController {

    // 从sb中获取控制器实例, 谁调用该方法, 就返回谁的实例对象
    static func controllerFromStoryboard(name: String, identifier: String) -> Self? {
        let sb = UIStoryboard(name: name, bundle: nil)
        if #available(iOS 13.0, *) {
            return sb.instantiateViewController(identifier: identifier)
        } else {
            // Fallback on earlier versions
            return sb.instantiateViewController(withIdentifier: identifier) as? Self
        }
    }

    // 从xib中获取控制器实例
//    static func controllerFromNib() -> Self {
//        return Self.init(nibName: String(describing: Self.self), bundle: nil)
//    }

    static var controllerFromNib: Self {
        return Self.init(nibName: String(describing: Self.self), bundle: nil)
    }
    
    static var xibController: Self {
        return Self.controllerFromNib
    }
}


/**
 * push & pop
 */
public extension UIViewController {

    func pushVC(viewController: UIViewController, animated: Bool = true) {
        navigationController?.pushViewController(viewController, animated: animated)
    }

    /**
     * 如果要push的vc是new出来 或者是从xib中取的, 就用这个
     *
     * 只能用来push没有重写init的控制器,
     * 如果重写了init , 系统自带的init方法就不提供了, 这样创建会报错
     */
    func pushVC<T: UIViewController>(vcClass: T.Type, animated: Bool = true) {

        
        let vc = vcClass.getVCInstance()
        pushVC(viewController: vc, animated: animated)
    }
    
    static func getVCInstance() -> Self {
        
        // 判断有无对应的xib, 如果有, 根据xib创建vc, 如果没有, new

        // 获取不带有target的vc名string
        let vcName = String(describing: Self.self)

        // 判断是否有对应的xib, 如果有, 注册xib, 否则注册cell
        // mlgb, 之前写 "cellName = cellClass.description(), \(cellName).xib" path一直拿不到...
        let path = Bundle.main.path(forResource: "\(vcName).nib", ofType: nil)
        
        if path == nil {

            // new控制器
            return Self.init()
        } else {

            // 根据xib创建控制器
            return Self.controllerFromNib
        }
    }

    func popVC(animated: Bool = true) {
        navigationController?.popViewController(animated: animated)
    }

    func close(animated: Bool = true, completion: (() -> Void)?) {

        if navigationController?.children.count ?? 0 > 1 {
            navigationController?.popViewController(animated: animated)
        } else {
            self.dismiss(animated: animated, completion: completion)
        }
    }
}





